/*-
 * Tension.java
 *
 * $LastChangedBy:  $
 * $LastChangedRevision:  $
 * $LastChangedDate:  $
 * $HeadURL: $
 *
 * Copyright (c) 2008, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.intention;

import java.io.IOException;
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.googlecode.attention.AttentionService;
import com.googlecode.attention.Local;
import com.googlecode.attention.Mobile;
import com.googlecode.attention.PhonebookEntry;
import com.googlecode.attention.PhonebookManager;
import com.googlecode.attention.SMSEntry;
import com.googlecode.attention.SMSManager;
import com.googlecode.attention.Status;
import com.googlecode.attention.intention.services.Extension;
import com.googlecode.attention.intention.services.SMSPoller;
import com.googlecode.attention.intention.tools.Phonebook;
import com.googlecode.attention.intention.tools.SMSEntryUtils;
import com.googlecode.attention.util.Settings;

import static com.googlecode.attention.intention.IntentionLogStatements.*;


public class Intention implements AttentionService {
  
  private Mobile mobile;
  private final String[] args;
  private Settings settings;
  
  private String lookupName;
  private String host;
  private int port;
  private boolean hasSMSCInfo;
  private boolean readPhonebook;
  private Phonebook phonebook;
  private String printPattern;
  private String patternSeparator;
  private String settingsLocation;
  private boolean isConfigured = false;
  
  public Intention(final String[] args) {
    this.args = args;
    readPhonebook = false;
    final String config = System.getProperty("intention.configuration");
    if (config != null) {
      settingsLocation = config;
    }
  }
  
  public void run() {
    parseArguments();
    if (isConfigured) {
      startPhonebook();
      startSecurityManager();
      getMobile();
      startExtension();
      if (readPhonebook) {
        final PhonebookEntry[] entries = getPhonebookEntries();
        phonebook.addEntries(entries);
        phonebook.dumpTo(System.out);
      } else {
        INTENTION_DEBUG.log("Listing SMS messages");
        final SMSEntry[] entries = getMessages();
        SMSEntryUtils.printMessages(entries, phonebook, hasSMSCInfo,
            printPattern, patternSeparator, System.out);
      }
    }
  }
  
  private void readConfiguration() {
    if (settings == null) {
      try {
        settings = new Settings(settingsLocation);
      } catch (IOException e) {
        INTENTION_007.log(settingsLocation, e);
        return;
      }
    }
    
    host = settings.getString("attention_host");
    port = settings.getInteger("attention_port");
    lookupName = settings.getString("attention_lookup_name");
    hasSMSCInfo = settings.getBoolean("has_smsc_info");
    printPattern = settings.getString("message_print_pattern");
    patternSeparator = settings.getString("message_print_pattern_separator");
    isConfigured = true;
  }
  
  private void startPhonebook() {
    phonebook = new Phonebook(settings);
    phonebook.readEntriesFromFile();
  }
  
  private void startExtension() {
    final SMSPoller poller = new SMSPoller(mobile, settings);
    final Thread pollerThread = new Thread(poller);
    pollerThread.start();
    final Extension extension = new Extension(poller, settings);
  }
  
  private PhonebookEntry[] getPhonebookEntries() {
    try {
      final PhonebookManager phonebookManager = mobile.getPhonebookManager();
      return phonebookManager.getPhonebookEntries();
    } catch (RemoteException e) {
      e.printStackTrace();
    }
    return new PhonebookEntry[0];
  }
  
  public void parseArguments() {
    for (int i = 0; i < args.length; i++) {
      final String arg = args[i].toLowerCase();
      if (arg.equals("-c") || arg.equals("--config-file")) {
        if (++i < args.length) {
          settingsLocation = args[i];
        }
      } else if (arg.equals("-rp") || arg.equals("--read-phonebook")) {
        readPhonebook = true;
      }
    }
    
    readConfiguration();
  }
  
  private void startSecurityManager() {
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }
  }
  
  private void getMobile() {
    mobile = Local.getInstance().getMobile(lookupName);
    
    if (mobile == null) {
      try {
        final Registry registry = LocateRegistry.getRegistry(host, port);
        mobile = (Mobile) registry.lookup(lookupName);
      } catch (ConnectException e) {
        e.printStackTrace(); // TODO log       
      } catch (RemoteException e) {
        e.printStackTrace(); // TODO log
      } catch (NotBoundException e) {
        e.printStackTrace(); // TODO log
      }
    }
  }
  
  private SMSEntry[] getMessages() {
    SMSEntry[] entries = null;
    if (mobile != null) {
      try {
        final SMSManager smsManager = mobile.getSMSManager();
        entries = smsManager.getMessages(Status.ALL_MESSAGES);
      } catch (RemoteException e) {
        e.printStackTrace(); // TODO log
      }
    }
    return (entries == null ? new SMSEntry[0] : entries);
  }
  
  public static void main(final String[] args) {
    final Intention intension = new Intention(args);
    intension.run();
  }
}
